package com.len.service;

import com.len.properties.OSSProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@Service
public class OSSService {

    @Resource
    private OSSProperties ossProperties;

    public String upload(MultipartFile multipartFile) throws IOException {

        if (multipartFile.isEmpty()) {
            return "文件为空，请选择一个文件上传。";
        }

        try {
            // 设置保存路径
            String uploadDirectory = "/opt/web/file/";
            File directory = new File(uploadDirectory);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 保存文件
            String fileName = multipartFile.getOriginalFilename();
            int dotIndex = fileName.lastIndexOf('.');
            if (dotIndex == -1) {
                throw new IOException("图片异常");
            }

            Assert.isTrue(Arrays.asList(ossProperties.getImageSuffix()).contains(fileName.substring(dotIndex + 1).toLowerCase()),"不支持的图片类型");

            fileName = fileName.substring(dotIndex + 1).toLowerCase();
            String random = UUID.randomUUID().toString().replace("-", "") + "." + fileName;
            String filePath = uploadDirectory + random;
            multipartFile.transferTo(Paths.get(filePath));
            return "http://154.204.44.133/web/file/" + random;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败：" + e.getMessage();
        }
    }

    public void delete(String objectName){

//        objectName = objectName.replace("https://"+ossProperties.getBucketName()+"."+ossProperties.getEndpoint()+"/","");
//        Assert.isTrue(StringUtils.isNotBlank(objectName),"删除文件名不能为空");
//
//        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
//        ossClient.deleteObject(ossProperties.getBucketName(),objectName);
//        // 关闭OSSClient。
//        ossClient.shutdown();
    }

}
